import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'umi';
import { Modal, List, Button } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';

let tempSelectData = [];

const SpecialZoneSelect = ({ value, dispatch, onChange, titleLabel = '', path, type, keyword }) => {
  const tableRef = useRef({});
  const [SelectModalVisible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [listData, setListData] = useState([]);

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      fixed: 'left',
      width: 64,
    },
    { title: '标题', align: 'center', dataIndex: `${keyword}` },
  ];

  useEffect(() => {
    if (value && Array.isArray(value)) {
      setListData(value);

      setSelectedRowKeys(
        value.map(item => {
          return { id: item.id, title: item.keyword };
        }),
      );
    }
  }, [value]);

  const changeListData = data => {
    setListData(data);
    onChange && onChange(data);
  };
  const getDataList = params =>
    new Promise(resolve => {
      dispatch({
        type: 'globalSpecialZone/getDataList',
        payload: { ...params, path, type },
        resolve,
      });
    });

  const deleteItem = item => {
    if (listData.indexOf(item) === -1) return;

    listData.splice(listData.indexOf(item), 1);
    changeListData([...listData]);
  };

  const handleOk = () => {
    const listMap = new Map();

    listData.forEach(item => {
      listMap.set(item.id, item.name ? item.name : item.title);
    });
    tempSelectData.forEach(item => {
      listMap.set(item.id, item.name ? item.name : item.title);
    });

    changeListData(
      Array.from(listMap).map(item => {
        return {
          id: item[0],
          title: item[1],
        };
      }),
    );
    setVisible(false);
  };

  return (
    <>
      <section className={styles.listContent}>
        <div className={styles.btnGroup}>
          <Button
            type="link"
            onClick={() => {
              setVisible(true);
            }}
          >
            添加
          </Button>
          <Button
            type="link"
            onClick={() => {
              changeListData([]);
            }}
          >
            清空
          </Button>
        </div>
        <div className={styles.listGroup}>
          <List
            size="small"
            dataSource={listData}
            renderItem={item => (
              <List.Item
                extra={
                  <CloseOutlined
                    className={styles.deleteBtn}
                    onClick={() => {
                      deleteItem(item);
                    }}
                  />
                }
              >
                {item.title}
              </List.Item>
            )}
          />
        </div>
      </section>
      <Modal
        title={`请选择${titleLabel}`}
        centered
        width="50vw"
        style={{ paddingBottom: 0 }}
        bodyStyle={{
          height: 'calc(95vh - 128px)',
          overflow: 'auto',
        }}
        visible={SelectModalVisible}
        onOk={handleOk}
        destroyOnClose
        okText="添加"
        onCancel={() => setVisible(false)}
      >
        <section
          style={{
            display: 'flex',
            flex: 'auto',
            boxSizing: 'border-box',
          }}
        >
          <section style={{ width: '100%', overflow: 'auto' }}>
            <ProTable
              rowKey="id"
              headerTitle="信息列表"
              actionRef={tableRef}
              rowSelection={{
                onChange: (keys, rows) => {
                  tempSelectData = rows;
                  setSelectedRowKeys(keys);
                },
                selectedRowKeys,
              }}
              scroll={{ x: 'max-content' }}
              request={async params => getDataList(params)}
              columns={columns}
            />
          </section>
        </section>
      </Modal>
    </>
  );
};

export default connect(({ global }) => ({
  enums: global.enums,
}))(SpecialZoneSelect);
